package ru.spb.xmlreshelper.screen.files;

import com.google.common.eventbus.Subscribe;
import org.apache.commons.lang3.math.NumberUtils;
import ru.spb.xmlreshelper.XmlResHelper;
import ru.spb.xmlreshelper.domain.CDTRecord;
import ru.spb.xmlreshelper.domain.ICdtService;
import ru.spb.xmlreshelper.gui.AbstractAppPanel;
import ru.spb.xmlreshelper.screen.cdt.CDTSelectionEvent;
import ru.spb.xmlreshelper.util.GuiUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author Nikita.Brazhnikov
 */
public class XmlXslSelectionPanel extends AbstractAppPanel {

    public static final String XSL_UPDATE_EVENT = XmlXslSelectionPanel.class.getName() + ".update.xsl";
    public static final String HTML_UPDATE_EVENT = XmlXslSelectionPanel.class.getName() + ".update.html";

    private JTextField cdtField;
    private JLabel cdtDescr;
    private CDTRecord selectedRecord;

    public XmlXslSelectionPanel() {
        build();
        GuiUtils.getEventBus().register(this);
    }


    private void build() {
        setLayout(new BorderLayout());
        JPanel cdtSelectionPanel = createCDTSelectionPanel();
        add(cdtSelectionPanel, BorderLayout.NORTH);

        JPanel filesStack = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 1.0;
        c.weighty = 0.0;
        c.anchor = GridBagConstraints.PAGE_START;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = 0;
        UpdateDownloadFilePanel xslPanel = new UpdateDownloadFilePanel(XSL_UPDATE_EVENT, "XSL") {
            @Override
            protected void performUpload(String filePath) {
                uploadFiles(getAndParseCdtId(), filePath, "xsl");
            }
        };
        xslPanel.setExtensionFilter("xsl");
        filesStack.add(xslPanel, c);
        UpdateDownloadFilePanel htmlPanel = new UpdateDownloadFilePanel(HTML_UPDATE_EVENT, "HTML") {
            @Override
            protected void performUpload(String filePath) {
                uploadFiles(getAndParseCdtId(), filePath, "html");
            }
        };
        htmlPanel.setExtensionFilter("html");
        c.gridy = 1;
        c.weighty = 1.0;
        filesStack.add(htmlPanel, c);


        add(filesStack, BorderLayout.CENTER);
        setBorder(BorderFactory.createTitledBorder("XSL/HTML files"));
    }

    private JPanel createCDTSelectionPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        //JPanel panel = new JPanel(new GridLayout(1,4));
        GridBagConstraints c = new GridBagConstraints();
        panel.add(new JLabel("CDT id"), c);
        cdtField = new JTextField(5);
        cdtField.setMinimumSize(new Dimension(100, cdtField.getPreferredSize().height));
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(0, 5, 0, 5);
        c.fill = GridBagConstraints.NONE;
        c.gridx = 1;
        c.weightx = 0.0;
        panel.add(cdtField, c);
        c.insets = new Insets(0, 0, 0, 0);
        JButton testBtn = new JButton("Test");
        testBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final Long cdtId = getAndParseCdtId();
                if (cdtId == -1)
                    return;
                SwingWorker sw = new SwingWorker() {
                    CDTRecord newRecord;

                    @Override
                    protected Object doInBackground() throws Exception {
                        try {
                            ICdtService service = XmlResHelper.getService(ICdtService.class);
                            newRecord = service.findCdt(cdtId);
                        } catch (Exception e) {
                            //TODO dialog
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void done() {
                        if (newRecord == null) {
                            cdtDescr.setText("CDT not found");
                        } else {
                            selectedRecord = newRecord;
                            updateCdtInfo(newRecord);
                        }
                    }
                };
                sw.execute();
            }
        });
        c.fill = GridBagConstraints.NONE;
        c.gridx = 2;
        panel.add(testBtn, c);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 3;
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        cdtDescr = new JLabel();
//        cdtDescr = new JTextArea(3, 70);
//        cdtDescr.setEditable(false);
//        cdtDescr.setLineWrap(true);
        //  cdtDescr.setVisible(false);
        panel.add(cdtDescr, c);
        panel.setBorder(BorderFactory.createTitledBorder("CDT"));
        return panel;
    }

    private Long getAndParseCdtId() {
        return NumberUtils.toLong(cdtField.getText(), -1l);
    }

    @Subscribe
    public void setSelectedCdt(CDTSelectionEvent cdtEvent) {
        selectedRecord = cdtEvent.getSelectedRecord();
        cdtField.setText(selectedRecord.getCdt().toString());
        updateCdtInfo(selectedRecord);
    }

    private void updateCdtInfo(CDTRecord record) {
        StringBuilder sb = new StringBuilder("<html>");
        sb.append(record.getName());
        sb.append(" {").append(record.getNamespace()).append("}");
        sb.append("</html>");
        cdtDescr.setText(sb.toString());
    }

    public void uploadFiles(Long cdt, String path, String type) {
        if (cdt == null || cdt < 0)
            return;
        ICdtService cdtService = XmlResHelper.getService(ICdtService.class);
        if ("xsl".equals(type)) {
            cdtService.updateXsl(cdt, path);
        } else if ("html".equals(type))
            cdtService.updateHtml(cdt, path);
    }

}
